// miniprogram/pages/applications/address/address.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address_list: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getAddressList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  goAddAddress() {
    wx.navigateTo({
      url: '../addaddress/addaddress',
    })
  },
  getUserAddress(e) {
    var idx = e.currentTarget.dataset.idx;
    var address = this.data.address_list;
    app.globalData.user_address = address[idx];
    var page=getCurrentPages();
    if (page[page.length - 2] == 'null' || page[page.length - 2] == 'undefined'){
      return false;
    }
    page[page.length - 2].onLoad();
    wx.navigateBack({
      delta:1,
    })
  },
  getAddressList() {
    let _this = this;
    let db = wx.cloud.database();
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        let openid = res.result.openid;
        db.collection('tb_address_list').where({
          _openid: openid
        }).get({
          success: resp => {
            for (let i = 0; i < resp.data.length; i++) {
              if (resp.data[i].isdefault) {
                app.globalData.user_address = resp.data[i];
              }
            }
            console.log(resp)
            _this.setData({
              address_list: resp.data
            })
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      fail: err => {

      }
    })

  },
  setDefaultAddress(e) {
    console.log(e);
    let id = e.currentTarget.dataset.id;
    let _this = this;
    let db = wx.cloud.database();
    db.collection('tb_address_list').where({
      isdefault: true
    }).get({
      success: res => {
        console.log(res)
        if (res.data.length > 0) {
          let ids = res.data[0]._id;
          wx.cloud.callFunction({
            name: 'updateDefaultAddress',
            data: {
              id: ids
            },
            success: res => {
              console.log(res)
              db.collection('tb_address_list').doc(id).update({
                data: {
                  isdefault: true
                },
                success: res => {
                  console.log(res)
                  _this.onLoad();
                },
                fail: err => {
                  console.log(err)
                }
              })
            },
            fail: err => {
              console.log(err)
            }
          })
        } else {
          db.collection('tb_address_list').doc(id).update({
            data: {
              isdefault: true
            },
            success: res => {
              console.log(res)
              _this.onLoad();
            },
            fail: err => {
              console.log(err)
            }
          })
        }

      },
      fail: err => {
        console.log(err)
      }
    });
  },
  deleteAddress(e) {
    let id = e.currentTarget.dataset.id;
    console.log(id);
    let db = wx.cloud.database();
    let _this = this;
    db.collection('tb_address_list').doc(id).remove({
      success: res => {
        console.log(res);
        if (res.stats.removed == 1) {
          wx.showToast({
            title: '删除成功',
          })
          _this.onLoad();
        } else {
          wx.showToast({
            title: '删除失败',
          })
        }

      },
      fail: err => {
        console.log(err)
      }
    })
  },
  asyncAddress() {
    let _this = this;
    let db = wx.cloud.database();
    wx.chooseAddress({
      success: res => {
        console.log(res)
        let data = {
          uname: res.userName,
          utelephone: res.telNumber,
          province: res.provinceName,
          city: res.cityName,
          area: res.countyName,
          detail: res.detailInfo,
          aarea: res.provinceName + '' + res.cityName + '' + res.countyName,
          isdefault: false,
        }
        db.collection('tb_address_list').add({
          data: data,
          success: res => {
            console.log(res)
            _this.onLoad()
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})